import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        //客户端端口需要系统自动分配
        //和服务器连接，需要知道服务器的IP和端口号
        //new对象的过程中，操作系统会自动进行3次握手，建立TCP连接
        socket = new Socket(serverIp, serverPort);
    }
    public void start() throws IOException {
        System.out.println("客户端上线！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner socketScanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scanner = new Scanner(System.in);
            while(true){
                //1.发送请求
                System.out.print("-> ");
                String request = scanner.next();
                printWriter.println(request);
                //写到内存后，需要使用flush方法，将内容写到网卡上去
                printWriter.flush();
                //2.接收服务器响应
                String response = socketScanner.next();
                //3.打印响应信息
                System.out.println(response);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9999);
        client.start();
    }
}
